import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui'
import Cate from './cate/cate'
import FoodList from './foodList/foodList'
import './food.scss'

export default class Food extends Component {
  constructor() {
    super(...arguments)
    this.state = {
      current: 0,
      tabList: [{ title: '点菜' }, { title: '评价' }, { title: '商家' }],
      foodList: [],
      currentList: [],
      selectCate: null
    }
  }

  changeTab(value) {
    this.setState({
      current: value
    })
  }

  changeCate(selectCate) {
    if (this.state.foodList.some(item => item.pid == selectCate.id)) {
      // 不用加载数据
      this.setState({
        currentList: this.state.foodList.filter(
          item => item.pid == selectCate.id
        )
      })
    } else {
      // 需要加载数据
      let foodList = this.getData(selectCate)
      setTimeout(() => {
        this.setState(
          {
            foodList: this.state.foodList.concat(foodList)
          },
          () => {
            this.setState({
              currentList: this.state.foodList.filter(
                item => item.pid == selectCate.id
              )
            })
          }
        )
      }, 0)
    }
    setTimeout(() => {
      this.setState({
        selectCate
      })
    }, 0)
  }

  // 模拟数据
  getData(selectCate) {
    let count = Math.floor(Math.random() * 2 + 1)

    return Array.from(Array(Math.floor(Math.random() * 5)), (v, i) => ({
      id: selectCate.id + '_' + i,
      pid: selectCate.id,
      imgId: count,
      price: Math.round(Math.random() * 20),
      sole: Math.round(Math.random() * 40),
      title: `分类${selectCate.id}菜品+${i + 1}`
    }))
  }

  renderTabPanel() {
    let { current, tabList, currentList, selectCate } = this.state
    console.log("TCL: Food -> renderTabPanel -> currentList", currentList)
    console.log('TCL: Food -> renderTabPanel -> tabList', tabList)

    return tabList.map((item, index) => {
      if (index === 0) {
        return (
          <AtTabsPane key={index} current={current} index={index}>
            <View className='food-cate'>
              <Cate onChangeCate={this.changeCate.bind(this)} />
              <FoodList selectCate={selectCate} currentList={currentList} />
            </View>
          </AtTabsPane>
        )
      }
      return (
        <AtTabsPane key={index} current={current} index={index}>
          <View>标签页{item.title}的内容</View>
        </AtTabsPane>
      )
    })
  }

  render() {
    let { current, tabList, currentList, selectCate } = this.state

    return (
      <AtTabs
        current={current}
        tabList={tabList}
        onClick={this.changeTab.bind(this)}
      >
        {this.renderTabPanel()}
      </AtTabs>
    )
  }
}
